package com.deepblue.image.maker.handler;

import com.deepblue.image.maker.websocket.WebsocketSessionCache;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ProgressMessage;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;

/**
 * websocket 日志打印
 *
 * @author yymagicer
 * @version 1.0
 * @date 2021/11/10 上午11:16
 */
public class WebsocketPrintHandler extends AbstractLoggingPrintHandler{

    private WebsocketSessionCache websocketSessionCache;


    public  WebsocketPrintHandler(WebsocketSessionCache websocketSessionCache){
        this.websocketSessionCache = websocketSessionCache;
    }

    public  WebsocketPrintHandler(WebsocketSessionCache websocketSessionCache,String sendUser){
        this.websocketSessionCache = websocketSessionCache;
        super.sendUser = sendUser;
    }

    @Override
    void sendLog(ProgressMessage message,String sendUser) throws DockerException {

        if (message.error() != null) {
            throw new DockerException(message.toString());
        }
        try {
            websocketSessionCache.get(sendUser).sendMessage(new TextMessage(message.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
